<template>
  <div>
    <div class="mb-3">
      <el-button
        type="primary"
        v-if="customerData.project_status === '0' || customerData.project_status === '2'"
        @click="addKeyvendor"
      >
        新增担保信息
      </el-button>
    </div>

    <h5 class="card-title" style="margin-top: 50px">反担保方式(保证)</h5>
    <loading-wrap>
      <el-table border :data="tableData">
        <el-table-column label="保证类型" align="center">
          <template slot-scope="scope">{{ enumPledge[scope.row.warrant_way] }}</template>
        </el-table-column>
        <el-table-column label="单位/企业名称" align="center" prop="warrant_name"></el-table-column>
        <el-table-column
          prop="warrant_own_name"
          label="姓名/企业名称"
          align="center"
        ></el-table-column>
        <el-table-column
          label="身份证/统一社会信用代码"
          align="center"
          prop="id_card"
        ></el-table-column>
        <el-table-column label="收入(元)" align="center" prop="warrant_value"></el-table-column>
        <el-table-column prop="remark" label="备注" align="center"></el-table-column>
        <el-table-column
          align="center"
          fixed="right"
          label="操作"
          v-if="customerData.project_status === '0' || customerData.project_status === '2'"
        >
          <template slot-scope="scope">
            <el-button class="py-0 px-1" type="text" @click="edit(scope.row)">
              <i class="fa fa-edit"></i>
            </el-button>
            <el-button
              class="py-0 px-1 text-danger"
              type="text"
              @click="deleteData(scope.row, 'tableData')"
            >
              <i class="fa fa-trash"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </loading-wrap>

    <div class="d-flex mb-3" style="margin-top: 30px">
      <h5 class="card-title">反担保方式(质押)</h5>
    </div>
    <loading-wrap>
      <el-table border :data="pledgeData">
        <el-table-column label="质押类型" align="center">
          <template slot-scope="scope">{{ enumZhiya[scope.row.warrant_way] }}</template>
        </el-table-column>
        <el-table-column label="企业名称" align="center" prop="warrant_name"></el-table-column>
        <el-table-column
          prop="warrant_own_name"
          label="所有权姓名/企业名称"
          align="center"
        ></el-table-column>
        <el-table-column
          label="身份证/统一社会信用代码"
          align="center"
          prop="id_card"
        ></el-table-column>
        <el-table-column label="比例(%)" align="center" prop="warrant_value"></el-table-column>
        <el-table-column prop="remark" label="备注" align="center"></el-table-column>
        <el-table-column
          align="center"
          fixed="right"
          label="操作"
          v-if="customerData.project_status === '0' || customerData.project_status === '2'"
        >
          <template slot-scope="scope">
            <el-button class="py-0 px-1" type="text" @click="pledge(scope.row)">
              <i class="fa fa-edit"></i>
            </el-button>
            <el-button
              class="py-0 px-1 text-danger"
              type="text"
              @click="deleteData(scope.row, 'pledgeData')"
            >
              <i class="fa fa-trash"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </loading-wrap>

    <div class="d-flex mb-3" style="margin-top: 30px">
      <h5 class="card-title">反担保方式(抵押)</h5>
    </div>
    <loading-wrap>
      <el-table border :data="mortgageData">
        <el-table-column label="抵押类型" align="center">
          <template slot-scope="scope">{{ enumDiya[scope.row.warrant_way] }}</template>
        </el-table-column>
        <el-table-column label="抵押物名称" align="center" prop="warrant_name"></el-table-column>
        <el-table-column
          prop="warrant_own_name"
          label="所有权姓名/企业名称"
          align="center"
        ></el-table-column>
        <el-table-column label="抵押物证件号" align="center" prop="id_card"></el-table-column>
        <el-table-column
          label="抵押物面积/型号"
          align="center"
          prop="warrant_model"
        ></el-table-column>
        <el-table-column
          prop="warrant_value"
          label="抵押物原值/面值"
          align="center"
        ></el-table-column>
        <el-table-column label="估值(万元)" align="center" prop="warrant_evalue"></el-table-column>
        <el-table-column label="抵押率(%)" align="center" prop="pledge_rate"></el-table-column>
        <el-table-column prop="remark" label="备注" align="center"></el-table-column>
        <el-table-column prop="address" label="地址" align="center"></el-table-column>
        <el-table-column
          align="center"
          fixed="right"
          label="操作"
          v-if="customerData.project_status === '0' || customerData.project_status === '2'"
        >
          <template slot-scope="scope">
            <el-button class="py-0 px-1" type="text" @click="mort(scope.row)">
              <i class="fa fa-edit"></i>
            </el-button>
            <el-button
              class="py-0 px-1 text-danger"
              type="text"
              @click="deleteData(scope.row, 'mortgageData')"
            >
              <i class="fa fa-trash"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </loading-wrap>

    <el-dialog
      title="反担保方式"
      width="95%"
      :close-on-click-modal="false"
      :before-close="handleClose"
      :visible.sync="dialogVisible"
    >
      <div>
        <div style="overflow: scroll">
          <table class="table table-bordered">
            <colgroup>
              <col width="10%" />
              <col width="9%" />
              <col width="9%" />
              <col width="9%" />
              <col width="9%" />
              <col width="9%" />
              <col width="9%" />
              <col width="9%" />
              <col width="9%" />
              <col width="9%" />
              <col width="9%" />
            </colgroup>
            <tr>
              <td colspan="2">反担保方式</td>
              <td colspan="3">
                <el-radio v-model="warrant_type" label="1">保证</el-radio>
              </td>
              <td colspan="3">
                <el-radio v-model="warrant_type" label="2">质押</el-radio>
              </td>
              <td colspan="3">
                <el-radio v-model="warrant_type" label="3">抵押</el-radio>
              </td>
            </tr>

            <template v-if="warrant_type === '1'">
              <tr>
                <td>保证类型</td>
                <td colspan="2">单位/企业名称</td>
                <td colspan="2">姓名/企业名称</td>
                <td colspan="2">身份证/统一社会信用代码</td>
                <td>收入(元)</td>
                <td colspan="2">备注</td>
                <td>操作</td>
              </tr>
              <tr v-for="(p, index) of PostData" :key="`pod-` + index">
                <td>
                  <el-select placeholder="请选择" v-model="p.warrant_way" clearable>
                    <el-option key="1" label="个人" value="1"></el-option>
                    <!-- <el-option key="2"
                               label="上下游客户"
                               value="2"></el-option> -->
                    <el-option key="17" label="企业" value="17"></el-option>
                    <el-option key="3" label="其他" value="3"></el-option>
                  </el-select>
                </td>
                <td colspan="2">
                  <el-input placeholder="单位/企业名称" v-model="p.warrant_name"></el-input>
                </td>
                <td colspan="2">
                  <el-input placeholder="姓名/企业名称" v-model="p.warrant_own_name"></el-input>
                </td>
                <td colspan="2">
                  <el-input placeholder="身份证/统一社会信用代码" v-model="p.id_card"></el-input>
                </td>
                <td>
                  <el-input placeholder="收入(元)" v-model="p.warrant_value"></el-input>
                </td>
                <td colspan="2">
                  <el-input placeholder="备注" v-model="p.remark"></el-input>
                </td>
                <td>
                  <el-button class="py-0 px-1 text-danger" type="text" @click="deleteOne(index)">
                    <i class="fa fa-trash"></i>
                  </el-button>
                </td>
              </tr>
            </template>
            <template v-else-if="warrant_type === '2'">
              <tr>
                <td>质押类型</td>
                <td colspan="2">企业名称</td>
                <td colspan="2">所有权姓名/企业名称</td>
                <td colspan="2">身份证/统一社会信用代码</td>
                <td>比例</td>
                <td colspan="2">备注</td>
                <td>操作</td>
              </tr>
              <tr v-for="(p, index) of pledgedata" :key="`posd-` + index">
                <td>
                  <el-select placeholder="请选择" v-model="p.warrant_way" clearable>
                    <el-option key="14" label="股权" value="14"></el-option>
                    <!-- <el-option key="13"
                               label="经营权"
                               value="13"></el-option> -->
                    <el-option key="16" label="受益权" value="16"></el-option>
                    <el-option key="15" label="其它" value="15"></el-option>
                  </el-select>
                </td>
                <td colspan="2">
                  <el-input placeholder="企业名称" v-model="p.warrant_name"></el-input>
                </td>
                <td colspan="2">
                  <el-input
                    placeholder="所有权姓名/企业名称"
                    v-model="p.warrant_own_name"
                  ></el-input>
                </td>
                <td colspan="2">
                  <el-input placeholder="身份证/统一社会信用代码" v-model="p.id_card"></el-input>
                </td>
                <td>
                  <el-input-number
                    :controls="false"
                    style="width: 105px"
                    placeholder="比例"
                    v-model="p.warrant_value"
                  ></el-input-number>
                </td>
                <td colspan="2">
                  <el-input placeholder="备注" v-model="p.remark"></el-input>
                </td>
                <td>
                  <el-button class="py-0 px-1 text-danger" type="text" @click="deleteOne(index)">
                    <i class="fa fa-trash"></i>
                  </el-button>
                </td>
              </tr>
            </template>
            <template v-else-if="warrant_type === '3'">
              <tr>
                <td>抵押类型</td>
                <td>抵押物名称</td>
                <td>所有权姓名/企业名称</td>
                <td>抵押物证件号</td>
                <td>抵押物面积/型号</td>
                <td>抵押物原值/面值</td>
                <td>估值(万元)</td>
                <td>抵押率</td>
                <td>地址</td>
                <td>备注</td>
                <td>操作</td>
              </tr>
              <tr v-for="(p, index) of mortgagedata" :key="`mostd-` + index">
                <td>
                  <el-select placeholder="请选择" v-model="p.warrant_way" clearable>
                    <el-option key="6" label="房产" value="6"></el-option>
                    <el-option key="7" label="设备" value="7"></el-option>
                    <el-option key="8" label="车产" value="8"></el-option>
                    <el-option key="9" label="土地" value="9"></el-option>
                    <el-option key="18" label="其它" value="18"></el-option>
                  </el-select>
                </td>
                <td>
                  <el-input placeholder="抵押物名称" v-model="p.warrant_name"></el-input>
                </td>
                <td>
                  <el-input
                    placeholder="所有权姓名/企业名称"
                    v-model="p.warrant_own_name"
                  ></el-input>
                </td>
                <td>
                  <el-input placeholder="抵押物证件号" v-model="p.id_card"></el-input>
                </td>
                <td>
                  <el-input placeholder="抵押物面积/型号" v-model="p.warrant_model"></el-input>
                </td>
                <td>
                  <el-input placeholder="抵押物原值/面值" v-model="p.warrant_value"></el-input>
                </td>
                <td>
                  <el-input placeholder="估值(万元)" v-model="p.warrant_evalue"></el-input>
                </td>
                <td>
                  <el-input-number
                    :controls="false"
                    style="width: 105px"
                    placeholder="抵押率"
                    v-model="p.pledge_rate"
                  ></el-input-number>
                </td>
                <td>
                  <el-input placeholder="地址" v-model="p.address"></el-input>
                </td>
                <td>
                  <el-input placeholder="备注" v-model="p.remark"></el-input>
                </td>
                <td>
                  <el-button class="py-0 px-1 text-danger" type="text" @click="deleteOne(index)">
                    <i class="fa fa-trash"></i>
                  </el-button>
                </td>
              </tr>
            </template>
          </table>
        </div>
        <div v-if="warrant_type === '1'">
          <el-button @click="PostData.push({})" style="margin-top: 15px">新增一行</el-button>
          <el-button v-loading="saveLoading" style="margin-top: 15px" @click="clearClose">
            取消
          </el-button>
          <el-button
            v-loading="saveLoading"
            style="margin-top: 15px"
            type="primary"
            @click="submitData"
          >
            保存
          </el-button>
        </div>
        <div v-if="warrant_type === '2'">
          <el-button @click="pledgedata.push({})" style="margin-top: 15px">新增一行</el-button>
          <el-button v-loading="saveLoading" style="margin-top: 15px" @click="clearClose">
            取消
          </el-button>
          <el-button
            v-loading="saveLoading"
            style="margin-top: 15px"
            type="primary"
            @click="pledgrSubmit"
          >
            保存
          </el-button>
        </div>
        <div v-if="warrant_type === '3'" v-loading="industloading">
          <el-button @click="mortgagedata.push({})" style="margin-top: 15px">新增一行</el-button>
          <el-button v-loading="saveLoading" style="margin-top: 15px" @click="clearClose">
            取消
          </el-button>
          <el-button
            v-loading="saveLoading"
            style="margin-top: 15px"
            type="primary"
            @click="mortgageSubmit"
          >
            保存
          </el-button>
        </div>
      </div>
    </el-dialog>

    <form-component
      title="保证"
      :visible.sync="tableVisible"
      :table-name="tableName"
      :form-data="formData"
      :formAppend="{ customer_id: 'customer_id' }"
      :table-id="tableId"
      :table-data="editData"
      :auto-init="false"
      @success="getData(params.index)"
    ></form-component>

    <form-component
      title="质押"
      :visible.sync="pledgeVisible"
      :table-name="tableName"
      :form-data="pleData"
      :formAppend="{ customer_id: 'customer_id' }"
      :table-id="tableId"
      :table-data="editData"
      :auto-init="false"
      @success="getData(params.index)"
    ></form-component>

    <form-component
      title="抵押"
      :visible.sync="mortVisible"
      :table-name="tableName"
      :form-data="mortData"
      :formAppend="{ customer_id: 'customer_id' }"
      :table-id="tableId"
      :table-data="editData"
      :auto-init="false"
      @success="getData(params.index)"
    ></form-component>
  </div>
</template>

<script>
import {
  enumPledge,
  enumWarrantWayType,
  enumWarrantType,
  enumZhiya,
  enumDiya,
} from '@/credit/plugins/enum'
import FormComponent from '@/components/FormComponent'
export default {
  components: {
    FormComponent,
  },
  props: {},
  data() {
    return {
      enumPledge,
      enumWarrantWayType,
      enumWarrantType,
      enumZhiya,
      enumDiya,
      tableName: 'datum_customer_warrant',
      tableData: [],
      pledgeData: [],
      pledgedata: [{}],
      mortgageData: [],
      mortgagedata: [{}],
      tableId: '',
      editData: {},
      dialogVisible: false,
      PostOne: {},
      PostData: [{}],
      saveLoading: false,
      warrant_type: '',
      mortVisible: false,
      industloading: false,
      mortData: {
        warrant_way: {
          type: 'radio',
          value: '',
          label: '抵押类型',
          required: true,
          enumType: enumDiya,
          inline: true,
        },
        warrant_name: { type: 'text', value: '', label: '抵押物名称' },
        warrant_own_name: { type: 'text', value: '', label: '所有权姓名/企业名称' },
        id_card: { type: 'text', value: '', label: '抵押物证件号' },
        warrant_model: { type: 'text', value: '', label: '抵押物面积/型号' },
        warrant_value: { type: 'text', value: '', label: '抵押物原值/面值' },
        warrant_evalue: { type: 'text', value: '', label: '估值' },
        pledge_rate: { type: 'text', value: '', label: '抵押率' },
        address: { type: 'text', value: '', label: '地址' },
        remark: { type: 'text', value: '', label: '备注' },
      },
      pledgeVisible: false,
      pleData: {
        warrant_way: {
          type: 'radio',
          value: '',
          label: '质押类型',
          required: true,
          enumType: enumZhiya,
          inline: true,
        },
        warrant_name: { type: 'text', value: '', label: '企业名称' },
        warrant_own_name: { type: 'text', value: '', label: '所有权姓名/企业名称' },
        id_card: { type: 'text', value: '', label: '身份证/统一社会信用代码' },
        warrant_value: { type: 'text', value: '', label: '比例' },
        remark: { type: 'text', value: '', label: '备注' },
      },
      tableVisible: false,
      formData: {
        warrant_way: {
          type: 'radio',
          value: '',
          label: '保证类型',
          required: true,
          enumType: enumPledge,
          inline: true,
        },
        warrant_name: { type: 'text', value: '', label: '单位/企业名称' },
        warrant_own_name: { type: 'text', value: '', label: '姓名/企业名称' },
        id_card: { type: 'text', value: '', label: '身份证/统一社会信用代码' },
        warrant_value: { type: 'text', value: '', label: '收入' },
        remark: { type: 'text', value: '', label: '备注' },
      },
    }
  },
  computed: {},
  watch: {},
  created() {
    this.customerData = JSON.parse(sessionStorage.getItem('customer_related_view'))
    this.id = this.$route.query.id || sessionStorage.getItem('customer_related_id')
    this.getData()
  },
  mounted() {},
  methods: {
    addKeyvendor() {
      this.dialogVisible = true
      this.warrant_type = '1'
    },
    editOne(index) {
      this.PostOne = this.PostData[index]
      this.deleteOne(index)
    },
    deleteOne(index) {
      this.PostData.splice(index, 1)
    },
    clearClose() {
      this.dialogVisible = false
    },
    handleClose() {
      this.dialogVisible = false
    },
    edit(p) {
      this.tableVisible = true
      this.tableId = p ? p.id : ''
      this.editData = p
    },
    pledge(p) {
      this.pledgeVisible = true
      this.tableId = p ? p.id : ''
      this.editData = p
    },
    mort(p) {
      this.mortVisible = true
      this.tableId = p ? p.id : ''
      this.editData = p
    },
    getData() {
      this.tableData = []
      this.pledgeData = []
      this.mortgageData = []
      this.$api
        .getData(
          'credit',
          this.tableName,
          {
            'customer_related_id.eq': this.id,
          },
          { warrant_way: 'asc' }
        )
        .then(res => {
          if (!res.data) {
            return
          }
          for (let p of res.data) {
            if (p.warrant_type === '1') {
              this.tableData.push(p)
            } else if (p.warrant_type === '2') {
              this.pledgeData.push(p)
            } else {
              this.mortgageData.push(p)
            }
          }
        })
      // this.gettableData()
      // this.getpledgeData()
      // this.getmortgageData()
    },
    // gettableData() {
    //   this.$api.getData('credit', this.tableName, {
    //     'customer_related_id.eq': this.id
    //   }).then(res => {
    //     if (!res.data) { return }
    //     for (let p of res.data) {
    //       if (p.warrant_type  === '1') {
    //         this.tableData.push(p)
    //       }
    //     }
    //   })
    // },
    // getpledgeData() {
    //   this.$api.getData('credit', this.tableName, {
    //     'customer_related_id.eq': this.id
    //   }).then(res => {
    //     if (!res.data) { return }
    //     for (let p of res.data) {
    //       if (p.warrant_type  === '2') {
    //         this.pledgeData.push(p)
    //       }
    //     }
    //   })
    // },
    // getmortgageData() {
    //   this.$api.getData('credit', this.tableName, {
    //     'customer_related_id.eq': this.id
    //   }).then(res => {
    //     if (!res.data) { return }
    //     for (let p of res.data) {
    //       if (p.warrant_type  === '3') {
    //         this.mortgageData.push(p)
    //       }
    //     }
    //   })
    // },
    async submitData() {
      if (this.PostData.length < 1) {
        this.handleClose()
        return
      }
      let customerData = {}
      const localCustomerData = sessionStorage.getItem('customer_related_view')
      try {
        customerData = JSON.parse(localCustomerData)
      } catch (e) {
        console.error(e)
      }
      for (let p of this.PostData) {
        p.customer_related_id = this.id
        p.customer_id = customerData.customer_id
        p.warrant_type = this.warrant_type
      }
      this.saveLoading = true
      const [res, err] = await this.$utils.promise(
        this.$api.addBatch('credit', this.tableName, this.PostData)
      )
      this.saveLoading = false
      if (res) {
        this.$message.success('数据采集成功！')
        this.getData()
        this.handleClose()
        this.PostData = []
      } else {
        this.$message.error(`数据采集失败，请重试！（${err.status}）`)
      }
    },
    async pledgrSubmit() {
      if (this.pledgedata.length < 1) {
        this.handleClose()
        return
      }
      let customerData = {}
      const localCustomerData = sessionStorage.getItem('customer_related_view')
      try {
        customerData = JSON.parse(localCustomerData)
      } catch (e) {
        console.error(e)
      }
      for (let p of this.pledgedata) {
        p.customer_related_id = this.id
        p.customer_id = customerData.customer_id
        p.warrant_type = this.warrant_type
      }
      this.saveLoading = true
      const [res, err] = await this.$utils.promise(
        this.$api.addBatch('credit', this.tableName, this.pledgedata)
      )
      this.saveLoading = false
      if (res) {
        this.$message.success('数据采集成功！')
        this.getData()
        this.handleClose()
        this.pledgedata = []
      } else {
        this.$message.error(`数据采集失败，请重试！（${err.status}）`)
      }
    },
    async mortgageSubmit() {
      let customerData = {}
      let data = []
      for (let p of this.mortgagedata) {
        if (JSON.stringify(p) !== '{}') {
          const localCustomerData = sessionStorage.getItem('customer_related_view')
          try {
            customerData = JSON.parse(localCustomerData)
          } catch (e) {
            console.error(e)
          }
          p.customer_id = customerData.customer_id
          p.customer_related_id = this.id
          p.warrant_type = this.warrant_type
          data.push(p)
        }
      }
      if (data.length > 0) {
        this.tomortSave(data)
      }
    },
    async tomortSave(data) {
      this.industloading = true
      const [res, err] = await this.$utils.promise(
        this.$api.addBatch('credit', this.tableName, data)
      )
      this.industloading = false
      if (res) {
        this.$message.success('数据采集成功！')
        this.getData()
        this.handleClose()
        this.mortgagedata = []
      } else {
        this.$message.error(`数据采集失败，请重试！（${err.status}）`)
      }
    },
    deleteData(item, key) {
      const h = this.$createElement
      this.$msgbox({
        title: '提示',
        message: h('span', undefined, `确定删除？`),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '删除中...'
            let res = ''
            if (key === 'mortgageData') {
              res = await this.$utils.promise(
                this.$api.deleteData('credit', this.tableName, item.id)
              )
            } else if (key === 'tableData') {
              res = await this.$utils.promise(
                this.$api.deleteData('credit', this.tableName, item.id)
              )
            } else {
              res = await this.$utils.promise(
                this.$api.deleteData('credit', this.tableName, item.id)
              )
            }
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'
            if (res) {
              this.$message.success('删除成功！')
              this.getData()
              // location.reload(true)
              done()
            } else {
              this.$message.error('删除失败，请重试！')
            }
          } else {
            done()
          }
        },
      }).catch(() => {})
    },
  },
}
</script>

<style scoped>
.table td {
  vertical-align: middle;
}
</style>
